package com.ylz.sjzx.sio.sdk.client.core.socketio;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.ylz.sjzx.sio.common.core.constant.IMConstant;
import com.ylz.sjzx.sio.common.core.core.IAdapter;
import com.ylz.sjzx.sio.common.core.core.SioBase;
import com.ylz.sjzx.sio.common.core.core.container.common.annotation.AdapterDesc;
import com.ylz.sjzx.sio.common.core.enums.Cmd;
import com.ylz.sjzx.sio.sdk.client.core.IMNioBase;
import com.ylz.sjzx.sio.sdk.client.session.IMSession;
import com.ylz.sjzx.sio.sdk.client.utils.SessionUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author wiqi
 * @version 1.0
 * @date 2020/12/21
 */
@Component
@Slf4j
public class FinalSocketIoEventHandler {

    public static final String USER = "user";
    public static final String SOCKETTYPE = "socketType";

    /**
     * 客户端连接的时候触发
     *
     * @param client
     */
    @SneakyThrows
    @OnConnect
    public void onConnect(SocketIOClient client) {
        IMNioBase.clean();
        SioBase.clean();
        client.set(IMConstant.IMSESSIONID, UUID.randomUUID().toString());
        IMNioBase.getSocketIOClientMap().put(client.get(IMConstant.IMSESSIONID), client);
        //存储SocketIOClient，用于发送消息

        Map<String, String> loginURlMap = new HashMap(3);
        loginURlMap.put(USER, client.getHandshakeData().getSingleUrlParam(USER));
        loginURlMap.put(SOCKETTYPE, client.getHandshakeData().getSingleUrlParam(SOCKETTYPE));
        if (loginURlMap.get(USER) == null) {
            client.disconnect();
            return;
        }
        IMSession session = SessionUtil.parse2Session(client, loginURlMap);
        IMNioBase.setSession(session);

        //存入本地变量
        IMNioBase.getGlobalSession().put(session.getSid(), session);
        log.info("OnConnect连接用户{}连接URl{}", session, client.getHandshakeData().getUrlParams());
        //login 直接处理
        IAdapter iAdapter = SioBase.getInnerAdapterMap().get(Cmd.login.getValue());
        //将接口的desc注解存入context
        SioBase.setIAdapterDesc(iAdapter.getClass().getAnnotation(AdapterDesc.class));
        iAdapter.invoke();
    }

    /**
     * 客户端关闭连接时触发
     *
     * @param client
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        log.debug("退出拉{}", client.get(IMConstant.IMSESSIONID).toString());

        //清除登录信息
        SessionUtil.getIMSessionService().logout(client.get(IMConstant.IMSESSIONID));
    }
}
